package cn.jdemo.pattern.object_pool;

import java.util.HashSet;
import java.util.Set;

/**
 *
 * @description
 * @date 2021/1/28
 */
public abstract class ObjectPool<T> {
    private Set<T> available = new HashSet<>();
    private Set<T> inUse = new HashSet<>();

    protected abstract T create();

    public synchronized T checkOut(){
        if (available.isEmpty()){
            available.add(create());
        }
        T next = available.iterator().next();
        available.remove(next);
        inUse.add(next);
        return next;
    }

    public synchronized void putIn(T t){
        inUse.remove(t);
        available.add(t);
    }
}
